package com.ruoyi.web.controller.system;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysLoginCheckConfig;
import com.ruoyi.system.mapper.SysLoginCheckConfigDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 登陆次数管理
 * @author chengjian 
 * @date 2021/10/19
 */
@RestController
@RequestMapping(value = "/system/check")
public class SysCheckLoginController {
    @Resource
    private TokenService tokenService;

    @Resource
    private SysLoginCheckConfigDao sysLoginCheckConfigDao;


    @PreAuthorize("@ss.hasPermi('system:check:list')")
    @GetMapping(value = "/list")
    public Page<SysLoginCheckConfig> getCheckInfo(HttpServletRequest request, String username){
        LoginUser loginUser = tokenService.getLoginUser(request);
        Page<SysLoginCheckConfig> page;

        if (loginUser.getUser().isAdmin()){
            page = sysLoginCheckConfigDao.selectPage(new Page<>(1,10),new QueryWrapper<>());
            QueryWrapper<SysLoginCheckConfig> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(username)){
                queryWrapper.lambda().eq(SysLoginCheckConfig::getUsername,username);
            }
            long count = sysLoginCheckConfigDao.selectCount(queryWrapper);
            page.setTotal(count);
            return page;
        }

        String account = loginUser.getUser().getUserName();
        page = sysLoginCheckConfigDao.selectPage(new Page<>(1,10),new LambdaQueryWrapper<SysLoginCheckConfig>().eq(SysLoginCheckConfig::getUsername,account));
        page.setTotal(1);
        return page;
    }

    @PreAuthorize("@ss.hasPermi('system:check:edit')")
    @GetMapping(value = "/apply/{id}")
    public AjaxResult apply(@PathVariable(value = "id") Integer id){
        SysLoginCheckConfig config = sysLoginCheckConfigDao.selectById(id);
        if (StringUtils.isNotEmpty(config.getExtendCode())){
            return AjaxResult.success("不需要重复申请扩展码",false);
        }

        config.setExtendCode(RandomUtil.randomString(8));
        config.setAgreeNum(config.getAgreeNum()+1);
        sysLoginCheckConfigDao.updateById(config);

        return AjaxResult.success("申请成功",true);
    }

    @Resource
    private SmsUtil smsUtil;

    public boolean sendSmsCode(String phoneNumber, String code) {
        Map<String,String> templateParams= new LinkedHashMap<>(1);
        templateParams.put("code",code);
        try {
            return smsUtil.sendSmsByDefaultSignName(phoneNumber, "SMS_137400127", templateParams);
        } catch (ClientException e) {
            return false;
        }
    }
}
